package jlxy.ise.eroad.service;

import java.util.List;
import java.util.Map;
import jlxy.ise.eroad.util.SqlOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 例子，其余的service照着写
 *
 * @author yecq
 */
@Service
@Transactional
public class SampleService {

    @Autowired
    private SqlOperator sql;

    // 添加用户
    public Sret add(String username, String passwd) {
        String stmt = "insert into user(username, passwd) values (?,?)";
        String id = this.sql.insert(stmt, username, passwd)[0];
        Sret sr = new Sret();
        sr.setOk();
        sr.setData(id);
        return sr;
    }

    // 列出所有用户用户
    public Sret list() {
        String stmt = "select * from user";
        List list = this.sql.query(stmt);
        Sret sr = new Sret();
        sr.setOk();
        sr.setData(list);
        return sr;
    }

    // 删除用户
    public Sret remove(String id) {
        String stmt = "delete from user where id = ?";
        this.sql.delete(stmt, id);
        Sret sr = new Sret();
        sr.setOk();
        return sr;
    }

    //查找用户
    public String search(String id) {
        String stmt = "select * from user where id =?";
        List list = sql.query(stmt, id);
        String passwd, username;
        Map m = (Map) list.get(0);
        passwd = (String) (m.get("passwd"));
        username = (String) (m.get("username"));
        return "username:" + username + ";passwd" + passwd;
    }

    public String searchUser(String username, String passwd) {
        String result=null;
        String stmt = "select * from user where username=? and passwd=?";
        List list = sql.query(stmt, username, passwd);
        if(list.isEmpty()){
            result="error";
        }else{
            result="welcome";
        }
        return result;
    }

    public Sret exception1() {
        throw new IllegalArgumentException("抛出异常1");
    }

    public Sret exception2() {
        throw new IllegalStateException("异常2");
    }
}
